package com.ff.xyh.access.service.impl.access;

import com.ff.xyh.common.entity.result.ResultMessage;
import com.ff.xyh.serurity.entity.CurrentUser;
import com.ff.xyh.serurity.entity.SecurityUser;
import com.ff.xyh.common.entity.useraccess.AccessUser;
import com.ff.xyh.access.service.access.AccessPermissionService;
import com.ff.xyh.access.service.access.AccessUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;


/**
 * <p>
 * 自定义userDetailsService - 认证用户详情
 * </p>
 *
 * @author qy
 * @since 2019-11-08
 */
@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private AccessUserService accessUserService;

    @Autowired
    private AccessPermissionService accessPermissionService;

    /***
     * 根据用户名(不一定 看看存的是什么)获取用户信息
     * 在 TokenAuthenticationFilter.getAuthentication 方法返回处存入
     * 返回后会在SpringSecurity中做识别
     * 识别成功后调用 TokenLoginFilter中的successfulAuthentication方法
     * @param userToken:
     * @return: org.springframework.security.core.userdetails.UserDetails
     */
    @Override
    public UserDetails loadUserByUsername(String userToken) throws UsernameNotFoundException {
        // 从数据库中取出用户信息
        AccessUser accessUser = accessUserService.getAccessUserWithUserToken(userToken);

        // 判断用户是否存在
        if (null == accessUser){
            throw new UsernameNotFoundException(ResultMessage.NO_SUCH_OBJECT);
        }
        // 返回UserDetails实现类
        CurrentUser currentUser = new CurrentUser();
        BeanUtils.copyProperties(accessUser,currentUser);
        currentUser.setUserToken(userToken);
//        System.out.println("loadUserByUsername ");
        // 获取权限列表
        List<String> authorities = accessPermissionService.selectPermissionValueListByUserId(accessUser.getId());
//        System.out.println("authorities ======>  " + authorities);
        SecurityUser securityUser = new SecurityUser(currentUser);
        securityUser.setPermissionValueList(authorities);
        return securityUser;
    }



}
